package com.dxw.kit.email;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.NewsAddress;

public class MailSender {
	
	private Properties props = new Properties();
	private ReadProperties mailProperties = null;
	

	public MailSender() {
		mailProperties = new ReadProperties("/mail.properties");
		props.put("mail.transport.protocol", mailProperties.getProperties("mail.transport.protocol"));
		props.put("mail.smtp.host", mailProperties.getProperties("mail.smtp.host"));
		props.put("mail.smtp.port", mailProperties.getProperties("mail.smtp.port"));
		props.put("mail.smtp.auth", mailProperties.getProperties("mail.smtp.auth"));
				
		//SSL
//		props.put("mail.smtp.starttls.enable", mailProperties.getProperties("mail.smtp.starttls.enable"));
//		props.put("mail.smtp.socketFactory.class", mailProperties.getProperties("mail.smtp.socketFactory.class"));
//		props.put("mail.smtp.socketFactory.port", mailProperties.getProperties("mail.smtp.socketFactory.port"));
//		props.put("mail.smtp.socketFactory.fallback", mailProperties.getProperties("mail.smtp.socketFactory.fallback"));
		
	}
	
	
	public MailSender(String mailPropertiesPath) {
		mailProperties = new ReadProperties(mailPropertiesPath);
		props.put("mail.transport.protocol", mailProperties.getProperties("mail.transport.protocol"));
		props.put("mail.smtp.host", mailProperties.getProperties("mail.smtp.host"));
		props.put("mail.smtp.port", mailProperties.getProperties("mail.smtp.port"));
		props.put("mail.smtp.auth", mailProperties.getProperties("mail.smtp.auth"));
		
		//SSL
//		props.put("mail.smtp.starttls.enable", mailProperties.getProperties("mail.smtp.starttls.enable"));
//		props.put("mail.smtp.socketFactory.class", mailProperties.getProperties("mail.smtp.socketFactory.class"));
//		props.put("mail.smtp.socketFactory.port", mailProperties.getProperties("mail.smtp.socketFactory.port"));
//		props.put("mail.smtp.socketFactory.fallback", mailProperties.getProperties("mail.smtp.socketFactory.fallback"));
	}

	/**
	 * sendTextMail发送UTF-8的文本型邮件<br>
	 * sendMail(mailMessage, "plain", "UTF-8");<br>
	 * @param mailMessage<br>
	 * @return boolean true(成功)/false(失败)<br>
	 */
	public boolean sendTextMail(MailMessage mailMessage) {
		return sendMail(mailMessage, "plain", "UTF-8");
	}
	
	/**
	 * sendTextMail发送指定编码格式charset的文本型邮件<br>
	 * sendMail(mailMessage, "plain", charset);<br>
	 * @param mailMessage<br>
	 * @param charset(编码格式) value="UTF-8"/"GBK"<br>
	 * @return boolean true(成功)/false(失败)<br>
	 */
	public boolean sendTextMail(MailMessage mailMessage, String charset) {
		return sendMail(mailMessage, "plain", charset);
	}

	/**
	 * sendHtmlMail发送UTF-8的HTML型邮件<br>
	 * sendMail(mailMessage, "html", "UTF-8");<br>
	 * @param mailMessage<br>
	 * @return boolean true(成功)/false(失败)<br>
	 */
	public boolean sendHtmlMail(MailMessage mailMessage) {
		return sendMail(mailMessage, "html", "UTF-8");
	}
	
	/**
	 * sendHtmlMail发送指定编码格式charset的HTML型邮件<br>
	 * sendMail(mailMessage, "html", charset)<br>
	 * @param mailMessage<br>
	 * @param charset(编码格式) value="UTF-8"/"GBK"<br>
	 * @return boolean true(成功)/false(失败)<br>
	 */
	public boolean sendHtmlMail(MailMessage mailMessage, String charset) {
		return sendMail(mailMessage, "html", charset);
	}
	
	/**
	 * sendMail默认发送UTF-8的HTML格式的邮件<br>
	 * sendMail(mailMessage, "html", "UTF-8");<br>
	 * @param mailMessage<br>
	 * @return boolean true(成功)/false(失败)<br>
	 */
	public boolean sendMail(MailMessage mailMessage) {
		return sendMail(mailMessage, "html", "UTF-8");
	}
	
	/**
	 * sendMail发送指定内容类型和编码格式的邮件
	 * @param mailMessage  
	 * @param contextType(内容类型)  value= "html"(网页)/"plain"(文本)
	 * @param charset(编码格式) value="UTF-8"/"GBK"
	 * @return boolean true(成功)/false(失败)
	 */
	public boolean sendMail(MailMessage mailMessage, String contextType, String charset) {
		String mailContentCharset = "text/" + contextType + "; charset=" + charset ;
		boolean bool = false;
		
		try {
			//邮件认证
			MailAuthenticator mailAuthenticator = null;
			mailAuthenticator = new MailAuthenticator(mailProperties.getProperties("mail.user"), mailProperties.getProperties("mail.password"));
			Session session = Session.getDefaultInstance(props, mailAuthenticator);
			//设置发送邮件为debug模式
			session.setDebug(Boolean.valueOf(mailProperties.getProperties("mail.debug")));
			
			Message message = new MimeMessage(session);
			
			//邮件fromMail（邮件发送者）,邮件发送者nickName（呢称）
			//从配置文件获取from（邮件发送者）
			String from = mailProperties.getProperties("mail.from");
			//如果邮件信息中from（邮件发送者）不为空，则使用邮件信息里的from
			if(null != mailMessage.getFrom() && "" != mailMessage.getFrom().trim() ) {
				from = mailMessage.getFrom();
			}
			//从配置文件中获取nickName（邮件发送者（呢称））
			String nickName =  mailProperties.getProperties("mail.nickName");
			///如果邮件信息中nickName（邮件发送者（呢称））不为空，则使用邮件信息里的nickName（邮件发送者（呢称））
			if(null != mailMessage.getNickName() && "" != mailMessage.getNickName().trim() ) {
				nickName = mailMessage.getNickName();
			}
			try {
				message.setFrom(new InternetAddress(from, nickName));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
						
			
			//指明邮件的收件人
			//message.setRecipient(Message.RecipientType.TO, new InternetAddress("163qq@qq.com"));
			for(String to : mailMessage.getToList()) {
				message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
			}
			for(String cc : mailMessage.getCcList()) {
				message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
			}
			for(String bcc : mailMessage.getBccList()) {
				message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc));
			}
			
			//邮件的标题
			message.setSubject(mailMessage.getSubject());
			
			//邮件整体内容
			//邮件主体（Multipart multipart）
			Multipart multipart = new MimeMultipart();
			//邮件主内容（BodyPart bodypart）
			BodyPart bodyPart = new MimeBodyPart();
			//设置内容和格式
			bodyPart.setContent(mailMessage.getContent(),mailContentCharset);
			multipart.addBodyPart(bodyPart);
			
			//添加附件
			for(File attach : mailMessage.getAttachs()) {
				BodyPart fileBodyPart = new MimeBodyPart();
				DataSource dataSource = new FileDataSource(attach);
				fileBodyPart.setDataHandler(new DataHandler(dataSource));
				fileBodyPart.setFileName(attach.getName());
				multipart.addBodyPart(fileBodyPart);
			}
			
			message.setContent(multipart,mailContentCharset);
			//发送邮件
			Transport.send(message);
			bool = true;
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bool;
	}

}
